package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.*;
import com.jmp.feign.AppIndexGoodsFeign;
import com.jmp.feign.BannerFeign;
import com.jmp.service.api.admin.AppIndexGoodsApi;
import com.jmp.service.api.admin.BannerApi;
import com.jmp.service.api.admin.dto.AppIndexGoodsRequest;
import com.jmp.service.api.admin.dto.AppIndexGoodsResponse;
import com.jmp.service.api.admin.dto.BannerListDto;
import com.jmp.service.api.admin.dto.BannerListVo;
import com.jmp.util.LabelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.ConvertUtils;
import one.stand.dto.GoodsTypeDto;
import one.stand.dto.PageResponse2;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiCrmJxsMapper;
import one.stand.model.Company;
import one.stand.model.Goods;
import one.stand.model.GoodsType;
import one.stand.model.ResultModel;
import one.stand.service.*;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api(description = "APP-首页")
@RestController
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private AppIndexGoodsFeign appIndexGoodsFeign;
    @Autowired
    private BannerFeign bannerFeign;

    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private CompanyBaseService companyBaseService;

    @Autowired
    private GoodsApiCrmJxsMapper goodsApiCrmJxsMapper;

    /**
     * @deprecated 新的接口(new)
     */
    @ApiOperation(value = "banner、icon、card")
    @GetMapping
    @Deprecated
    public ResultModel<IndexResponse> index(@RequestAttribute IndexRequest request) {
        //banner
        List<IndexResponse.Banner> banners = Lists.newArrayList(IndexResponse.Banner.builder()
                .source("https://file.hongmushichang.com/2769806014951/photo/730079385289228288.jpg")
                .event(BannerApi.EVENT_H5)
                .eventId("https://apps.apple.com/cn/app/%E8%8A%B1%E5%9B%AD%E8%B4%AD/id1490129458")
                .memo("展销会通知")
                .build());

        //精选品牌
        List<IndexResponse.Banner> iconBannerList = getBannerList(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_BRAND, null);

        //海报
        List<IndexResponse.Banner> cardBannerList = getBannerList(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_INDEX_CARD, null);

        IndexResponse response = IndexResponse.builder()
                .bannerList(banners)
                .iconList(iconBannerList)
                .cardList(cardBannerList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "banner、icon、card")
    @GetMapping("new")
    public ResultModel<IndexNewResponse> indexNew(@RequestAttribute IndexRequest request) {
        //banner
        List<IndexNewResponse.Banner> banners = getBannerList2(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_INDEX, null);

        //精选品牌
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(BannerApi.COMPANY_ID_PLATFORM)
                .bannerType(BannerApi.BANNER_TYPE_JSX_BRAND_2)
                .refId(null)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        List<IndexNewResponse.Icon> iconList = ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), type -> {
            return IndexNewResponse.Icon.builder()
                    .name(type.getMemo())
                    .children(getBannerList2(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_BRAND_2, type.getId()))
                    .build();
        });

        //海报
        List<IndexNewResponse.Banner> cardBannerList = getBannerList2(BannerApi.COMPANY_ID_PLATFORM, BannerApi.BANNER_TYPE_JSX_INDEX_CARD, null);

        IndexNewResponse response = IndexNewResponse.builder()
                .bannerList(banners)
                .iconList(iconList)
                .cardList(cardBannerList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("商品列表")
    @GetMapping("/goods")
    public ResultModel<IndexGoodsResponse> goods(@RequestAttribute IndexGoodsRequest request) {

        AppIndexGoodsRequest goodsRequest = AppIndexGoodsRequest.builder()
                .type(AppIndexGoodsApi.TYPE_INDEX)
                .build();
        goodsRequest.setPageNum(request.getPageNum());
        goodsRequest.setPageSize(request.getPageSize());
        ResultModel<AppIndexGoodsResponse> resultModel = appIndexGoodsFeign.list(goodsRequest);
        AssertUtil.isTrue(resultModel);

        PageResponse2<AppIndexGoodsResponse.Goods> goodsPage = resultModel.getData().getGoodsList();
        if (OneListUtil.isNotEmpty(goodsPage.getList())) {
            Collections.shuffle(goodsPage.getList());
        }

        PageResponse2<IndexGoodsResponse.Goods> goodsList = ConvertUtils.page2(goodsPage, goods -> {
            List<GoodsTypeDto> platformTypes = goodsBaseService.getTypes(goods.getGoodsId());
            if (OneListUtil.isEmpty(platformTypes)) return null;

            Goods goods1 = goodsBaseService.get(goods.getGoodsId());
            Long popularityNum = recordPublicService.getPopularity(SeeRecordEnums.PRODUCT.getCode(), goods1.getGoodsId());
            boolean hasVr = StringUtils.isNoneBlank(goods1.getQjVrUrl());
            boolean hasAr = goodsBaseService.hasAr(goods1.getGoodsId());
            boolean hasVideo = StringUtils.isNoneBlank(goods1.getVideoUrl());
            boolean hasZkgx = companyBaseService.hasZkgx(goods1.getCompanyId());
            Company company = companyBaseService.getById(goods1.getCompanyId());

            return IndexGoodsResponse.Goods.builder()
                    .goodsId(goods1.getGoodsId())
                    .goodsName(goods1.getGoodsName())
                    .photo(goodsPhotoService.getPath(goods1.getGoodsId()))
//                    .price(goods1.getShowPrice() == 1 ? MoneyUtil.getMoneyStr(goods1.getPrice()) : "价格详询客服")
                    .price("价格详询客服")
                    .popularityNum(popularityNum)
                    .labels(LabelUtil.getLabels(hasVr, hasAr, hasVideo, hasZkgx))
                    .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                    .companyName(Objects.nonNull(company) ? company.getCompanyName() : null)
                    .build();
        });

        IndexGoodsResponse response = IndexGoodsResponse.builder()
                .goodsPage(goodsList)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("搜索列表")
    @GetMapping("/search")
    public ResultModel<IndexSearchResponse> search(@RequestAttribute IndexSearchRequest request) {

        PageResponse2<Integer> goodsIds = null;
        String nameLike = SqlUtil.like(request.getName());
        if (Objects.nonNull(request.getBannerId())) {//搜索配置商品列表
            AppIndexGoodsRequest goodsRequest = AppIndexGoodsRequest.builder()
                    .type(AppIndexGoodsApi.TYPE_CATEGORY)
                    .refId(request.getBannerId())
                    .nameLike(nameLike)
                    .build();
            goodsRequest.setPageNum(request.getPageNum());
            goodsRequest.setPageSize(request.getPageSize());
            ResultModel<AppIndexGoodsResponse> responseResultModel = appIndexGoodsFeign.list(goodsRequest);
            AssertUtil.isTrue(responseResultModel);
            goodsIds = ConvertUtils.page2(responseResultModel.getData().getGoodsList(), AppIndexGoodsResponse.Goods::getGoodsId);
        } else {//搜索商品库
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            List<Integer> goodsIdList = goodsApiCrmJxsMapper.selectSearch(nameLike, request.getCompanyId(), request.getTypeId());
            goodsIds = ConvertUtils.page2(goodsIdList, id -> id);
        }

        PageResponse2<IndexSearchResponse.Goods> goodsList = ConvertUtils.page2(goodsIds, goodsId -> {
            List<GoodsTypeDto> platformTypes = goodsBaseService.getTypes(goodsId);
            if (OneListUtil.isEmpty(platformTypes)) return null;

            Goods goods = goodsBaseService.get(goodsId);
            GoodsType goodsType = goodsTypeService.get(goods.getGoodstypeId());
            Long popularityNum = recordPublicService.getPopularity(SeeRecordEnums.PRODUCT.getCode(), goods.getGoodsId());
            boolean hasVr = StringUtils.isNoneBlank(goods.getQjVrUrl());
            boolean hasAr = goodsBaseService.hasAr(goodsId);
            boolean hasVideo = StringUtils.isNoneBlank(goods.getVideoUrl());
            boolean hasZkgx = companyBaseService.hasZkgx(goods.getCompanyId());
            Company company = companyBaseService.getById(goods.getCompanyId());

            return IndexSearchResponse.Goods.builder()
                    .goodsId(goodsId)
                    .goodsName(goods.getGoodsName())
                    .photo(goodsPhotoService.getPath(goods.getGoodsId()))
//                    .price(goods.getShowPrice() == 1 ? MoneyUtil.getMoneyStr(goods.getPrice()) : "价格详询客服")
                    .price("价格详询客服")
                    .categoryName(goodsType.getGroupName())
                    .popularityNum(popularityNum)
                    .labels(LabelUtil.getLabels(hasVr, hasAr, hasVideo, hasZkgx))
                    .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                    .companyName(Objects.nonNull(company) ? company.getCompanyName() : null)
                    .build();
        });

        IndexSearchResponse response = IndexSearchResponse.builder()
                .goodsPage(goodsList)
                .build();
        return ResultModel.success(response);
    }

    private List<IndexResponse.Banner> getBannerList(Integer companyId, Integer bannerType, Integer refId) {
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(companyId)
                .bannerType(bannerType)
                .refId(refId)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        return ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> IndexResponse.Banner.builder()
                .source(companyBanner.getSource())
                .event(companyBanner.getEvent())
                .eventId(companyBanner.getEventId())
                .memo(companyBanner.getMemo())
                .build());
    }

    private List<IndexNewResponse.Banner> getBannerList2(Integer companyId, Integer bannerType, Integer refId) {
        BannerListDto bannerListDto = BannerListDto.builder()
                .companyId(companyId)
                .bannerType(bannerType)
                .refId(refId)
                .build();
        bannerListDto.setAll();
        ResultModel<BannerListVo> bannerListVoResultModel = bannerFeign.list(bannerListDto);
        AssertUtil.isTrue(bannerListVoResultModel);
        return ConvertUtils.list(bannerListVoResultModel.getData().getBannerPage().getList(), companyBanner -> IndexNewResponse.Banner.builder()
                .source(companyBanner.getSource())
                .event(companyBanner.getEvent())
                .eventId(companyBanner.getEventId())
                .memo(companyBanner.getMemo())
                .build());
    }
}
